package org.example.demo1;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import dao.StudentDao;
import pojo.Student;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
@WebServlet(name = "postAdd",value = "/pastadd")
public class Postadd extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse resp) throws IOException {
        request.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html");
//        创建一个new StringBuilder()对象用来读取存储json数据
        StringBuilder sb = new StringBuilder();
        try {
//            使用request.getReader();获取请求的输入流
            BufferedReader reader = request.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);//将数据存储在sb中
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String string = sb.toString();
//        创建gson对象
        Gson gson = new Gson();
//         使用fromJson()方法将请求内容转换成student对象
        Student student1 = gson.fromJson(string, Student.class);
      StudentDao studentDao = new StudentDao();
        int flag = studentDao.addStudents(student1);
//         创造hashmap
        HashMap<String, Object> hs = new HashMap<>();
        if (flag > 0) {
            hs.put("code", 200);
            hs.put("msg", "添加成功");
            hs.put("data", 1);

        } else {
            hs.put("code", 500);
            hs.put("msg", "添加失败");
            hs.put("data", 0);
        }
        String json = gson.toJson(hs);
        resp.getWriter().println(json);

    }
}


